var defaultEventIcon = "../img/defaultEventType.png";
var defaultTVIcon = "../img/defaultTV.png";
var defaultPartIcon = "../img/defaultPart.png";

var arcGisUrl = "http://39.107.125.44:6080";
var map;
var toolbar;
var partLayer;
var centerX = 106.638;//120.206354450751;
var centerY = 26.684;//30.0725834699399;
var currentGraphic;
var drawHandler;
var dynamicTowPointFiveD;
var extendScal = 10;

var registerPointType = "registerPointType";
var reportPointType = "reportPointType";
var tvPointType = "tvPointType";
var flickerPointType = "flickerPointType";
var partPointType = "partPointType";
var gridNetType = "gridNetType";

var newTempId = "registerTempId";
var flickerPointID = "flickerPointID";
var secondLayer;

var vec;
var veca;

require(
		[ "esri/map", "esri/Color", "esri/graphic", "esri/InfoTemplate",
				"esri/SpatialReference", "esri/renderers/HeatmapRenderer",
				// 控件
				"esri/dijit/OverviewMap", "esri/dijit/Scalebar",
				"esri/dijit/Measurement", "esri/units",
				// 图层
				"tdlib/TDTLayer", "tdlib/TDTAnnoLayer", "tdlib/TDT_ImgLayer",
				"tdlib/TDT_ImgAnnoLayer", "esri/layers/GraphicsLayer",
				"esri/layers/ArcGISDynamicMapServiceLayer",
				"esri/layers/ArcGISTiledMapServiceLayer",
				"esri/layers/FeatureLayer",
				// 图形要素
				"esri/geometry/Point", "esri/geometry/Polyline",
				"esri/geometry/Polygon", "esri/geometry/Circle",
				// 样式
				"esri/symbols/TextSymbol", "esri/symbols/SimpleMarkerSymbol",
				"esri/symbols/PictureMarkerSymbol",
				"esri/symbols/SimpleLineSymbol",
				"esri/symbols/SimpleFillSymbol",
				// 标签
				"esri/symbols/Font", "esri/layers/LabelClass",
				// 查询
				"esri/tasks/query", "esri/tasks/QueryTask",
				"esri/toolbars/draw", "esri/dijit/Popup",
				"esri/dijit/PopupTemplate", "dojo/dom", "dojo/dom-construct" ],
		function(Map, Color, Graphic, InfoTemplate, SpatialReference,
				HeatmapRenderer, OverviewMap, Scalebar, Measurement, Units,
				TDTLayer, TDTAnnoLayer, TDT_ImgLayer, TDT_ImgAnnoLayer,
				GraphicsLayer, ArcGISDynamicMapServiceLayer,
				ArcGISTiledMapServiceLayer, FeatureLayer, Point, Polyline,
				Polygon, Circle, TextSymbol, SimpleMarkerSymbol,
				PictureMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, Font,
				LabelClass, Query, QueryTask, Draw, Popup, PopupTemplate, dom,
				domConstruct) {

			map = new Map("map", {
				slider : false,
				logo : false,
				showLabels : true,
				center : [ centerX, centerY ],
				zoom : 17,
				minZoom : 8
			});

			// 初始化比例尺
			var scalebar = new Scalebar({
				map : map,
				attachTo : "bottom-left",
				scalebarUnit : "dual",
			});

			// 显示比例尺
			scalebar.show();
			drawHandler = Draw;
			vec = new TDTLayer();// 切片线画图
			veca = new TDTAnnoLayer();// 切片标注
			var img = new TDT_ImgLayer();
			var imga = new TDT_ImgAnnoLayer();
			map.addLayer(vec);
			map.addLayer(veca);

			dynamicTowPointFiveD = new ArcGISTiledMapServiceLayer(arcGisUrl
					+ "/arcgis/rest/services/ByMap/MapServer");
			dynamicTowPointFiveD.hide();
			dynamicTowPointFiveD.id = "dynamicTowPointFiveD";
			map.addLayer(dynamicTowPointFiveD);

			var url = arcGisUrl + "/arcgis/rest/services/ceshi2/MapServer";
			secondLayer = new FeatureLayer(url + "/15", {
				mode:FeatureLayer.MODE_SNAPSHOT,
				outFields : [ "*" ],
				maxScale : 0,
				minScale : 4508.935440959931,
				visible : true,
				id : "secondLayer"
			});
			map.addLayer(secondLayer);
			
			secondLayer.setMaxScale(0);
			secondLayer.setMinScale(4508.935440959931);
			

			map.graphics.on("mouse-down", function(evt) {
				console.log("graphicslayer:mouse-down");
				if (evt.graphic && evt.graphic.pointType == registerPointType) {
					currentGraphic = evt.graphic;
				} else {
					currentGraphic = null;
				}
				if (currentGraphic) {
					currentGraphic.isMouseDown = true;

					map.disableMapNavigation();
					map.disablePan();
				}
			});
			map.on("mouse-drag", function(evt) {
				console.log("map:mouse-drag");
				if (currentGraphic) {
					if (currentGraphic.isMouseDown) {
						currentGraphic.setGeometry(evt.mapPoint);

						// 同步移动报警点
						var geometry = flickerPoint.geometry;
						geometry.x = evt.mapPoint.x;
						geometry.y = evt.mapPoint.y;
						flickerPoint.setGeometry(geometry);
					}
				}

			});

			map
					.on(
							"mouse-up",
							function(evt) {
								console.log("map:mouse-up");
								if (currentGraphic) {
									map.enableMapNavigation();
									map.enablePan();
									currentGraphic.isMouseDown = false;
									console.log(currentGraphic.attributes.id);
									var currentGraphicTemp = currentGraphic;
									currentGraphic = null;

									$
											.springLemonDialog({
												content : '确认该位置为发生事件位置?',// 确认文本
												clickButton : function(sender,
														modal, index) {// 按钮事件处理
													if (index == 0) {

														// 设置坐标位置
														jQuery("#longitude")
																.val(
																		evt.mapPoint.x);
														jQuery("#latitude")
																.val(
																		evt.mapPoint.y);
														/*jQuery(
																"#registerEventAdress")
																.val(
																		evt.mapPoint.x
																				+ ":"
																				+ evt.mapPoint.y);*/
														getAdress(evt.mapPoint.x,evt.mapPoint.y);
														// 移动报警点位置
														/*
														 * createFlickerPoint({
														 * "id" :
														 * flickerPointID,
														 * "longitude" :
														 * evt.mapPoint.x,
														 * "latitude" :
														 * evt.mapPoint.y });
														 */
														if (currentGraphicTemp.attributes) {
															currentGraphicTemp.attributes.longitude = evt.mapPoint.x;
															currentGraphicTemp.attributes.latitude = evt.mapPoint.y;
														}
														if (flickerPoint.attributes) {
															flickerPoint.attributes.longitude = evt.mapPoint.x;
															flickerPoint.attributes.latitude = evt.mapPoint.y;
														}

														refreashMapBasicInfo(currentGraphicTemp);
														// getManagementPersonInfo($("#registerEventType").val(),$("#longitude").val(),$("#latitude").val());
														
														serverDataForUser.eventTypeId = $("#registerEventType").val();
														serverDataForUser.longitude = evt.mapPoint.x;
														serverDataForUser.latitude = evt.mapPoint.y;
														serverTableForUser
																.draw(false);

													} else {
														var mapPoint = currentGraphicTemp.geometry;
														mapPoint
																.setX(currentGraphicTemp.attributes.longitude);
														mapPoint
																.setY(currentGraphicTemp.attributes.latitude);
														currentGraphicTemp
																.setGeometry(mapPoint);

														// 同步移动报警点
														var geometry = flickerPoint.geometry;
														geometry
																.setX(flickerPoint.attributes.longitude);
														geometry
																.setY(flickerPoint.attributes.latitude);
														flickerPoint
																.setGeometry(geometry);
													}
													$(this).closeDialog(modal);
												}
											});
								}

							});

			toolbar = new Draw(map);
			dojo.connect(toolbar, "onDrawEnd", CheckToMap);

			getEventReportData($("#eventReportIdentify").val(), $(
					"#eventRegisterIdentify").val());
			/* $('body').everyTime('1s',test); */

			// return;
			// 防异步错误
			clearInterval(flashTime);
			// 单位数据刷新
			var flashTime = setInterval(function() {
				refreashFlickerPoint();
			}, 75);
		});
//添加事件点
jQuery('.addEventInMapBtn').on('click', function() {
	var icon =defaultEventIcon;
	$('body').css('cursor', 'url(' + icon + '),auto');
	map.setMapCursor('url(' + icon + '),auto');
	toolbar.activate(drawHandler.POINT);
	$(".addEventInMapBtn").attr("disabled", true);
	$(".searchPartInMapBtn").attr("disabled", true);
});

function refreashMapBasicInfo(currentGraphicTemp) {
	if($("#longitude").val()==""||$("#latitude").val()==""){
		return;
	}
	$
			.ajax({
				url : rootPath
						+ "/ui/eventRegister/getRealTimeEventIdentify?eventTypeId="
						+ $("#registerEventType").val() + "&longitude="
						+ $("#longitude").val() + "&latitude="
						+ $("#latitude").val(),
				dataType : 'json',
				type : 'get',
				contentType : "application/json",
				success : function(result) {
					if (result.data.codeForEventIdentify <= 0) {
						message("实时获取事件编码失败!");
					} else {
						$("#registerEventIdentify").val(
								result.data.eventIdentify);
					}
					if (result.data.codeForGrid <= 0) {
						message("实时获取网格失败!");
					} else {
						var temp_registerEventToNetGrid=$("#registerEventToNetGrid").val();
						if (result.data.gridInfo) {
							$("#registerEventToNetGridName").val(
									result.data.gridInfo.gridName);
							$("#registerEventToNetGrid").val(
									result.data.gridInfo.id);
						} else {
							$("#registerEventToNetGridName").val("");
							$("#registerEventToNetGrid").val("");
						}
						if(temp_registerEventToNetGrid!=$("#registerEventToNetGrid").val()){
							GetGridGrading($("#longitude").val(),$("#latitude").val());
						}
						if (currentGraphicTemp && currentGraphicTemp.attributes) {
							currentGraphicTemp.attributes.registerEventToNetGrid = result.data.gridInfo;
						}
						CreateAccorsbindingInfo(result.data.gridInfo,
								result.data.partInfo);
					}
				}
			});
};
//获取grading
function GetGridGrading(longitude,latitude) {
	$
			.ajax({
				url : rootPath
						+ "/ui/eventRegister/getGrading?"
						+ "&longitude="
						+ longitude + "&latitude="
						+ latitude,
				dataType : 'json',
				type : 'get',
				contentType : "application/json",
				success : function(result) {
					if (result.data.codeForGrid <= 0) {
						message("实时获取网格失败!");
					} else {
						initGradingLevel(result.data.gradings);
					}
				}
			});
};
//重新加载扣分层级选项
function initGradingLevel(gradings){

	$("#registerEventEvaluateLevel").empty();
	if(gradings){
		for(var i=0;i<gradings.length;i++){
			jQuery("#registerEventEvaluateLevel").append("<option value='"+gradings[i].id+"'>"+gradings[i].gradingName+"</option>"); 
		}
	}
	initevaluateLevelUserDetail("", $("#registerEventEvaluateLevel")
			.val(), $("#registerEventType").val(), $(
			"#registerEventToNetGrid").val());
}
function refreashFlickerPoint() {
	if (flickerPoint) {
		var symbol = flickerPoint.symbol;

		symbol.color.a -= 0.05;
		symbol.setSize(symbol.size + 8);

		if (symbol.color.a <= 0) {
			symbol.color.a = 1;
			symbol.setSize(1);
		}
		flickerPoint.setSymbol(symbol);
	}
}
var flickerPoint;
function createFlickerPoint(data) {

	var symbol = new esri.symbol.SimpleMarkerSymbol(
			esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, // 样式,STYLE_CIRCLE(●),STYLE_CROSS(+),STYLE_DIAMOND(◆),STYLE_SQUARE(■),STYLE_X(X)
			1, // 像素
			new esri.symbol.SimpleLineSymbol(
					esri.symbol.SimpleLineSymbol.STYLE_SOLID, // 样式,STYLE_DASH(破折号),STYLE_DASHDOT(点划线),STYLE_DASHDOTDOT,STYLE_DOT(点),STYLE_NULL,STYLE_SOLID(实线)
					new dojo.Color([ 255, 0, 0 ]), 0.1), // 颜色 1 // 像素 ),
			new dojo.Color([ 255, 0, 0, 1 ]) // 颜色和透明度
	);
	var myPoint = {
		"geometry" : {
			"type" : "point",
			"x" : data.longitude,
			"y" : data.latitude,
			"spatialReference" : {
				"wkid" : 4326
			}
		},
		"attributes" : data,
		"symbol" : symbol
	};
	var graphic = getcurrentGraphic(data.id, flickerPointType);

	if (graphic == null) {
		graphic = new esri.Graphic(myPoint);
		graphic.symbol = symbol;
		graphic.attributes = data;
		graphic.pointType = flickerPointType;
		map.graphics.add(graphic);

	} else {
		var geometry = graphic.geometry;
		geometry.x = data.longitude;
		geometry.y = data.latitude;

		graphic.attributes = data;
		graphic.pointType = flickerPointType;
		graphic.setGeometry(geometry);
		graphic.setSymbol(symbol);
	}
	flickerPoint = graphic;
	return graphic;
};
function getcurrentGraphic(data, pointType) {

	var graphics;

	if (pointType == registerPointType || pointType == reportPointType
			|| pointType == flickerPointType) {
		graphics = map.graphics.graphics;
	} else {
		graphics = secondLayer.graphics;
	}

	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i]) {
			if (graphics[i].attributes) {
				if (graphics[i].attributes.id == data) {
					return graphics[i];
				}
			}
		}
	}
	return null;
};

// 创建点
function createPoint(data, symbolurl, pointType) {

	if (symbolurl == ""
			&& (pointType == registerPointType || pointType == reportPointType)) {
		symbolurl = defaultEventIcon;
	} else if (symbolurl == "" && pointType == tvPointType) {
		symbolurl = defaultTVIcon;
	}

	var symbol = new esri.symbol.PictureMarkerSymbol(symbolurl, // 图标路径
	20, // 图标的宽度
	20);

	var myPoint = {
		"geometry" : {
			"type" : "point",
			"x" : data.longitude,
			"y" : data.latitude,
			"spatialReference" : {
				"wkid" : 4326
			}
		},
		"attributes" : data,
		"symbol" : symbol
	};
	var graphic = getcurrentGraphic(data.id, pointType);

	if (graphic == null) {
		graphic = new esri.Graphic(myPoint);
		graphic.symbol = symbol;
		graphic.attributes = data;
		graphic.pointType = pointType;

		if (pointType == registerPointType || pointType == reportPointType
				|| pointType == flickerPointType) {
			map.graphics.add(graphic);
		} else {
			secondLayer.add(graphic);
		}

	} else {
		var geometry = graphic.geometry;
		geometry.x = data.longitude;
		geometry.y = data.latitude;

		graphic.attributes = data;
		graphic.pointType = pointType;
		graphic.setGeometry(geometry);
		graphic.setSymbol(symbol);

	}

	// 中心化
	if (graphic.pointType == registerPointType) {
		map.centerAndZoom(graphic.geometry, map.getLevel());
	}
	return graphic;
};
// 通过id删除图层元素
function deleteGraphicById(data) {
	var graphics = map.graphics.graphics;
	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i]) {
			if (graphics[i].attributes) {
				if (graphics[i].attributes.id == data) {
					map.graphics.remove(graphics[i]);
					return;
				}
			}
		}
	}
}
// 创建与事件相关联的地图元素
function CreateAccorsbindingInfo(girdNetInfo, partInfos) {
	// 清除以前已经有了的信息网格、部件信息。
	/*
	 * var graphics = map.graphics.graphics; for (var i = 0; i <
	 * graphics.length; i++) { if (graphics[i]) { if (graphics[i].pointType ==
	 * registerPointType || graphics[i].pointType == reportPointType ||
	 * graphics[i].pointType == flickerPointType) { continue; }else{
	 * map.graphics.remove(graphics[i]); } } }
	 */
	secondLayer.clear();

	if (girdNetInfo) {
		createArea(girdNetInfo);
	}
	if (partInfos) {
		for (var i = 0; i < partInfos.length; i++) {
			var symbolurl = "../img/defaultPart.png";
			var pointType = "";

			if (partInfos[i].part && partInfos[i].part.partType
					&& partInfos[i].part.partType.value == "1") {
				pointType = tvPointType;
			} else {
				pointType = partPointType;
			}
			if (partInfos[i].part&&partInfos[i].part.iconAddress && partInfos[i].part.iconAddress != "") {
				symbolurl = window.rootPath + "/" + partInfos[i].part.iconAddress;
			}
			createPoint(partInfos[i], symbolurl, pointType);
		}
	}
}

// 创建图形
function createArea(data, isDivision) {
	if (data.details) {
		var rings = [];

		var points = [];

		for (var i = 0; i < data.details.length; i++) {
			points.push([]);
		}

		for (var i = 0; i < data.details.length; i++) {
			var point = [];
			point.push(data.details[i].longtitude);
			point.push(data.details[i].latitude);

			points[data.details[i].longlatOrder] = point;
		}
		rings.push(points);

		var symbol = getPolygonDefaultSymbol();

		var myPolygon = {
			"geometry" : {
				"rings" : rings,
				"spatialReference" : {
					"wkid" : 4326
				}
			},
			"symbol" : {
				"color" : [ 0, 0, 0, 64 ],
				"outline" : {
					"outline" : [ 0, 0, 0, 255 ],
					"width" : 1,
					"type" : "esriSLS",
					"style" : "esriSFSSolid"
				}
			}
		};

		var graphic = new esri.Graphic(myPolygon);
		graphic.symbol = symbol;
		graphic.attributes = data;
		graphic.gridDetails = data.details;
		graphic.pointType = gridNetType;
		secondLayer.add(graphic);
	}

};
// 显示指定分类的部件
function showAccorsbindingPart(pointType) {
	var graphics = secondLayer.graphics;
	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i]) {
			if (pointType == null || graphics[i].pointType == pointType) {
				graphics[i].show();
			} else {
				graphics[i].hide();
			}
		}
	}

}
// 显示监控点
jQuery('.showTVPointInMapBtn').on('click', function() {
	if (secondLayer) {
		if ($(".showTVPointInMapBtn").html() == "仅显示监控点") {
			showAccorsbindingPart(tvPointType);
			$(".showTVPointInMapBtn").html("显示所有部件");
		} else {
			showAccorsbindingPart(null);
			$(".showTVPointInMapBtn").html("仅显示监控点");
		}

	}
});
// 显示2.5D地图
jQuery('.showThreeDInMapBtn').on('click', function() {
	if (dynamicTowPointFiveD) {
		if ($(".showThreeDInMapBtn").html() == "2.5D展示") {
			dynamicTowPointFiveD.show();
			$(".showThreeDInMapBtn").html("2.5D隐藏");
		} else {
			dynamicTowPointFiveD.hide();
			$(".showThreeDInMapBtn").html("2.5D展示");
		}

	}
});
// 地图添加框选
jQuery('.searchPartInMapBtn').on('click', function() {
	toolbar.activate(drawHandler.EXTENT);
	$(".cancelPartInMapBtn").attr("disabled", false);
	$(".searchPartInMapBtn").attr("disabled", true);
	$('body').css('cursor', 'crosshair');
	map.setMapCursor('crosshair');
});
// 地图取消框选
jQuery('.cancelPartInMapBtn').on('click', function() {
	toolbar.deactivate(); // 关闭工具栏并激活地图导航.
	$(".cancelPartInMapBtn").attr("disabled", true);
	$(".searchPartInMapBtn").attr("disabled", false);
	$('body').css('cursor', 'default');
	map.setMapCursor('default');
});
// 分析框选结果
function CheckToMap(extent) {
	toolbar.deactivate(); // 关闭工具栏并激活地图导航.
	$(".cancelPartInMapBtn").attr("disabled", true);
	$(".searchPartInMapBtn").attr("disabled", false);

	$('body').css('cursor', 'default');
	map.setMapCursor('default');

	map.showZoomSlider(); // 在地图上显示的缩放滑块

	switch (extent.type) {
	case "point":
		$("#longitude").val(extent.x);
		$("#latitude").val(extent.y);
		
		createFlickerPoint({
			"id" : flickerPointID,
			"longitude" : extent.x,
			"latitude" : extent.y
		});
		createPoint({
			"id" : newTempId,
			"longitude" : extent.x,
			"latitude" : extent.y
		}, defaultEventIcon, registerPointType);
		getAdress(extent.x,extent.y);
		refreashMapBasicInfo(null);
		
		serverDataForUser.eventTypeId = $("#registerEventType").val();
		serverDataForUser.longitude = extent.x;
		serverDataForUser.latitude = extent.y;
		serverTableForUser
				.draw(false);
		break;
	case "extent":
		var graphics = secondLayer.graphics;
		var results = [];
		var ids = "";
		for (var i = 0; i < graphics.length; i++) {
			if (extent.contains(graphics[i].geometry) && graphics[i].attributes&&graphics[i].pointType==tvPointType) {// &&graphics[i].pointType==tvPointType
				results.push(graphics[i].attributes);
				ids += graphics[i].attributes.id + ",";
			}
		}
		jQuery('#videoModal').modal('show');
		//初始化参数
		currentResults=results;
		tvRow=1;
		tvColumn=1;
		TVwidthscale =12;
		TVheight =600;
		currentPageNum=1;
		$("#pageNum").html(currentPageNum);
		
		CreateTV(currentResults,currentPageNum);
		//$("#tvids").val(ids);
		break;
	}	
};
$("#nextPage").on("click",function(){
	if(!(currentResults.length>currentPageNum*tvRow*tvColumn)){
		alert("已经是最后一页");
	}else{
		currentPageNum++;
		CreateTV(currentResults,currentPageNum);
	}
});
$("#previousPage").on("click",function(){
	if(currentPageNum==1){
		alert("已经是第一页");
	}else{
		currentPageNum--;
		CreateTV(currentResults,currentPageNum);
	}
});
var tvRow=1;
var tvColumn=1;
var TVwidthscale =12;
var TVheight =600;
var currentPageNum=1;
var currentResults=[];
function CreateTV(results,pageNum)
{
	if(results.length>1){
		TVheight=285;
		tvColumn=2;
		tvRow=2;
		TVwidthscale=6;
	}else{
		TVheight=570;
		tvColumn=1;
		tvRow=1;
		TVwidthscale=12;
	}
	var isIECore='';
	if(!!window.ActiveXObject || "ActiveXObject" in window)
	    isIECore=true;
	else  
	    isIECore=false;
	
	var object_str="";
	
	if(results.length<=((pageNum-1)*tvColumn*tvRow)){
		return;
	}
	$("#pageNum").html(currentPageNum);
	$("#TVdiv").empty();
	for(var i=((pageNum-1)*tvColumn*tvRow);i<results.length;i++){
		if((i-((pageNum-1)*tvColumn*tvRow))>=4){
			break;
		}
		if (isIECore) {	
			object_str+='<div class="col-md-'+TVwidthscale+'" style="padding-left: 0px;padding-right: 0px;">'
				+'<div class="box box-info" style="margin-bottom: 0px;border-top-width: 0px;" id="'+i+'_td" useradress="'+results[i].interfaceAddress+'" userchannel="'+results[i].interfacePort+'">'
				+'<object id="'+i+'_csocx" classid="clsid:59EA8A50-4FC1-406a-A471-595247AB2E41" codebase="/wcsi/tvfile/CISDITV.cab" width="100%" height="'+TVheight+'px"></object></div></div>';
		}
		else {
			object_str+='<div class="col-md-'+TVwidthscale+'" style="padding-left: 0px;padding-right: 0px;">'
				+'<div class="box box-info" style="margin-bottom: 0px;border-top-width: 0px;" id="'+i+'_td" useradress="'+results[i].interfaceAddress+'" userchannel="'+results[i].interfacePort+'">'
				+'<object id="'+i+'_csocx" clsid="{59EA8A50-4FC1-406a-A471-595247AB2E41}" type="application/x-itst-activex"  progid="/wcsi/tvfile/CISDITV.cab" width="100%" height="'+TVheight+'px"></object></div></div>';
		}
	}
	$('#TVdiv').append(object_str);
	
	for(var i=((pageNum-1)*tvColumn*tvRow);i<results.length;i++){
		if((i-((pageNum-1)*tvColumn*tvRow))>=4){
			break;
		}
		WatchTV(i+"_csocx",i+"_td");
	}
};
function WatchTV(id,tdid)
{
	var ocxKq = document.getElementById(id);
	var ocxKqj =$("#"+tdid);
	var ip =ocxKqj.attr("useradress");
	var channel=ocxKqj.attr("userchannel");
	setTimeout(function(){
		ocxKq.InstallView(ip,channel);
		ocxKq.OpenStream();
	},500);
};
function getPolygonDefaultSymbol() {
	var symbol = new esri.symbol.SimpleFillSymbol(
			esri.symbol.SimpleFillSymbol.STYLE_SOLID,
			new esri.symbol.SimpleLineSymbol(
					esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([
							255, 0, 0 ]), 2), new dojo.Color([ 255, 145, 0,
					0.35 ]));

	return symbol;
}
/*
 * jQuery(document).ready( function() {
 * getEventReportData($("#eventReportIdentify").val(), $(
 * "#eventRegisterIdentify").val()); });
 */
var serverData = {};
var serverTable;

function initevaluateLevelUserDetail(eventRegisterIdentify, evaluateLevel,
		eventType, grid) {
	$("#myTabs").empty();
	$("#tabcontentdiv").empty();
	$
			.ajax({
				url : rootPath
						+ "/ui/eventRegister/getValuateLevelUserDetail?eventRegisterIdentify="
						+ eventRegisterIdentify + "&evaluateLevel="
						+ evaluateLevel + "&eventType=" + eventType + "&grid="
						+ grid,
				dataType : 'json',
				type : 'get',
				contentType : "application/json",
				success : function(result) {
					if (result.data.code <= 0) {
						message("记载数据失败！");
					} else {
						var data = result.data.list
						if (data) {
							

							var tabcontent = "";
							var htmlcontent = "";
							var currentId = "";
							for (var i = 0; i < data.length; i++) {
								for (var j = 0; j < data[i].length; j++) {
									currentId = data[0][0].eventToevaluateId;
									if (j == 0) {
										tabcontent += '<li class="markTab"><a href="#tab_'
												+ data[i][j].eventToevaluateId
												+ '" data-toggle="tab">'
												+ data[i][j].showtabName
												+ '</a></li>';
										htmlcontent += '<div class="tab-pane" id="tab_'
												+ data[i][j].eventToevaluateId
												+ '">'
												+ '<table class="table table-bordered">'
												+ '<tbody>';
										isOk = true;
									}
									if (j % 4 == 0) {
										htmlcontent += '<tr>';
									}

									htmlcontent += '<td width="8%" align="center">'
											+ data[i][j].name
											+ '</td>'
											+ '<td width="16%">'
											+ '<div class="col-md-9">'
											+ '<input userdefinedtype="'
											+ data[i][j].eventToevaluateId
											+ '" class="form-control  userdefinedEvaluate" type="text" value="'
											+ data[i][j].scale
											+ '" datatype="*,*1-11,t" nullmsg="请输入分值" onkeyup="clearNoNum(this)" id="'
											+ data[i][j].id
											+ '" />'
											+ '</div>'
											+ '<div class="col-md-1">'
											+ '<span style="color: #F00; fontsize: 30px">*</span>'
											+ '</div>' + '</td>';
									if (j % 4 == 0 && j != 0) {
										htmlcontent += '</tr>';
									}
									if (j == data[i].length - 1) {
										htmlcontent += '</tbody>'
												+ '</table></div>';
									}
								}
							}
							$("#myTabs").append(tabcontent);
							$("#tabcontentdiv").append(htmlcontent);
							$('#myTabs a[href="#tab_' + currentId + '"]').tab(
									'show');
						}
					}
				}
			});
};
function getEventReportData(eventReportIdentify, eventRegisterIdentify) {
	var data = {
		"eventReportIdentify" : eventReportIdentify,
		"eventRegisterIdentify" : eventRegisterIdentify
	}

	$
			.ajax({
				url : rootPath
						+ "/ui/eventRegister/getDetailInfo?eventReportIdentify="
						+ eventReportIdentify + "&eventRegisterIdentify="
						+ eventRegisterIdentify,
				dataType : 'json',
				data : JSON.stringify(data),
				type : 'get',
				contentType : "application/json",
				success : function(result) {
					if (result.data.code <= 0) {
						message("记载数据失败！");
					} else {
						if (result.data.eventRegister) {
							// 事件源
							var report = result.data.eventRegister.registerEventToReportEvent;
							if (report != undefined) {
								var iconAddress = "";
								if (report.reportEventType
										&& report.reportEventType.iconAddress
										&& report.reportEventType.iconAddress != "") {
									iconAddress = window.rootPath
											+ "/"
											+ report.reportEventType.iconAddress;
								}

								createPoint(report, iconAddress,
										reportPointType);

								$("#reportContent").val(report.reportContent);
								$("#reportMemo").val(report.reportMemo);
								$("#reportAccTime").val(
										moment(report.reportAccTime).format(
												'YYYY/MM/DD HH:mm'));

								if (report.reportUser) {
									$("#reportUser")
											.val(report.reportUser.name);
									$("#reportUserPhone").val(
											report.reportUser.contactType);
								}

								$("#reportImgAdress")
										.attr(
												"src",
												rootPath
														+ "/"
														+ report.reportImgAdress);

								$("#reportAdress").val(report.reportAdress);

								if (report.reportEventToNetGrid)
									$("#reportEventToNetGrid")
											.val(
													report.reportEventToNetGrid.gridName);

								if (report)
									$("#reportEventVariable").val(
											report.reportEventVariable.title);

								if (report.reportEventAttrVariable)
									$("#reportEventAttrVariable").val(
											report.reportEventAttrVariable.id);
								if (report.reportEventType)
									$("#reportEventType").val(
											report.reportEventType.eventName);
							}
							var register = result.data.eventRegister;

							var iconAddress = "";
							if (register.registerEventType
									&& register.registerEventType.iconAddress
									&& register.registerEventType.iconAddress != "") {
								iconAddress = window.rootPath
										+ "/"
										+ register.registerEventType.iconAddress;
							}
							createFlickerPoint({
								"id" : flickerPointID,
								"longitude" : register.longitude,
								"latitude" : register.latitude
							});
							createPoint(register, iconAddress,
									registerPointType);

							$("#eventRegisterIdentify").val(register.id);

							jQuery("#registerEventReportTime").val(moment(register.registerEventReportTime).format('YYYY-MM-DD'));
							jQuery("#dateTime").val(moment(register.registerEventReportTime).format('HH:mm'));
							// 事件类型
							if (register.registerEventType) {
								$("#registerEventTypeName").val(
										register.registerEventType.eventName);
								$("#registerEventType").val(
										register.registerEventType.id);
							}
							// 登记名称
							$("#registerEventName").val(
									register.registerEventName);
							// 事件编码
							$("#registerEventIdentify").val(
									register.registerEventIdentify);
							// 图片地址
							$("#registerEventImgAdress").attr(
									"src",
									rootPath + "/"
											+ register.registerEventImgAdress);
							if (register.registerEventEvaluateLevel) {
								$("#registerEventEvaluateLevel").val(
										register.registerEventEvaluateLevel.id);
							}
							// 严重程度
							if (register.registerEventSeriousLevel) {
								$("#registerEventSeriousLevel").val(
										register.registerEventSeriousLevel.id);
							}
							// 所属网格
							if (register.registerEventToNetGrid) {
								$("#registerEventToNetGrid").val(
										register.registerEventToNetGrid.id);
								$("#registerEventToNetGridName")
										.val(
												register.registerEventToNetGrid.gridName);
							}
							// 是否关联主键
							if (register.registerEventToPartBaseInfo) {
								$("#registerEventToPartBaseInfo")
										.val(
												register.registerEventToPartBaseInfo.id);
								$("#registerEventToPartBaseInfoName")
										.val(
												register.registerEventToPartBaseInfo.partName);
							}
							// 主管部门
							if (register.registerEventHierarchy) {
								$("#registerEventHierarchy").val(
										register.registerEventHierarchy.id);
								$("#registerEventHierarchyName")
										.val(
												register.registerEventHierarchy.groupName);
							}
							if (register.registerEventState) {
								$("#registerEventState").val(
										register.registerEventState.title);
							}
							$("#acceptLimitSpan").val(register.acceptLimitSpan);
							$("#dealLimitSpan").val(register.dealLimitSpan);
							$("#registerEventAdress").val(
									register.registerEventAdress);
							$("#longitude").val(register.longitude);
							$("#latitude").val(register.latitude);
							$("#registerEventContent").val(
									register.registerEventContent);
							$("#registerEventMemo").val(
									register.registerEventMemo);
							initevaluateLevelUserDetail($(
									"#eventRegisterIdentify").val(), $(
									"#registerEventEvaluateLevel").val(), $(
									"#registerEventType").val(), $(
									"#registerEventToNetGrid").val());

						} else if (result.data.eventReport) {
							// 事件源
							var report = result.data.eventReport;

							var iconAddress = "";

							if (report.reportEventType
									&& report.reportEventType.iconAddress
									&& report.reportEventType.iconAddress != "") {
								iconAddress = window.rootPath + "/"
										+ report.reportEventType.iconAddress;
							}
							createFlickerPoint({
								"id" : flickerPointID,
								"longitude" : report.longitude,
								"latitude" : report.latitude
							});
							createPoint(report, iconAddress, reportPointType);
							createPoint({
								"id" : newTempId,
								"longitude" : report.longitude,
								"latitude" : report.latitude
							}, iconAddress, registerPointType);

							jQuery("#registerEventReportTime").val(moment(report.reportAccTime).format('YYYY-MM-DD'));
							jQuery("#dateTime").val(moment(report.reportAccTime).format('HH:mm'));
							$("#reportContent").val(report.reportContent);
							$("#reportMemo").val(report.reportMemo);
							$("#reportAccTime").val(moment(report.reportAccTime).format('YYYY/MM/DD HH:mm'));

							if (report.reportUser) {
								$("#reportUser").val(report.reportUser.name);
								$("#reportUserPhone").val(
										report.reportUser.contactType);
							}

							$("#reportImgAdress").attr("src",
									rootPath + "/" + report.reportImgAdress);

							$("#reportAdress").val(report.reportAdress);

							if (report.reportEventToNetGrid) {
								$("#reportEventToNetGrid").val(
										report.reportEventToNetGrid.gridName);

								$("#registerEventToNetGridName").val(
										report.reportEventToNetGrid.gridName);
								$("#registerEventToNetGrid").val(
										report.reportEventToNetGrid.id);
							}

							if (report)
								$("#reportEventVariable").val(
										report.reportEventVariable.title);

							if (report.reportEventAttrVariable)
								$("#reportEventAttrVariable").val(
										report.reportEventAttrVariable.id);
							if (report.reportEventType) {
								$("#reportEventType").val(
										report.reportEventType.eventName);

								// 登记事件默认值
								$("#registerEventTypeName").val(
										report.reportEventType.eventName);
								$("#registerEventType").val(
										report.reportEventType.id);
								$("#acceptLimitSpan").val(
										report.reportEventType.acceptLimit);
								$("#dealLimitSpan").val(
										report.reportEventType.processLimit);

							}
							// 登记事件默认值
							$("#registerEventName").val(
									report.reportEventType.eventName);

							var tempUrl = report.reportImgAdress;
							if (tempUrl != "") {
								tempUrl = rootPath + "/"
										+ report.reportImgAdress;
							} else {
								tempUrl = "../img/upload.png";
							}
							$("#registerEventImgAdress").attr("src", tempUrl);
							if (result.data.state)
								$("#registerEventState").val(
										result.data.state.title);

							$("#registerEventAdress").val(report.reportAdress);
							$("#longitude").val(report.longitude);
							$("#latitude").val(report.latitude);
							$("#registerEventContent")
									.val(report.reportContent);
							$("#registerEventMemo").val(report.reportMemo);

							// 初始化扣分数据
							var evaluateLevel = $("#registerEventEvaluateLevel")
									.val();
							initevaluateLevelUserDetail("", evaluateLevel, $(
									"#registerEventType").val(), $(
									"#registerEventToNetGrid").val());

						} else {// 内部新创建一个事件
							$(".addEventInMapBtn").attr("disabled", false);
							$("#registerEventState").val("初始化");
							jQuery("#registerEventReportTime").val(getFormatDate());
							jQuery("#dateTime").val(getDateTime());
							initevaluateLevelUserDetail("", $(
									"#registerEventEvaluateLevel").val(), $(
									"#registerEventType").val(), $(
									"#registerEventToNetGrid").val());
						}

						refreashMapBasicInfo(null);
						getManagementPersonInfo($("#registerEventType").val(),
								$("#longitude").val(), $("#latitude").val());

						if ($("#registerEventState").val() == "初始化") {
							jQuery(".saveEventBtn").prop("disabled", false);
							jQuery(".submitEventBtn").prop("disabled", false);
							showInput(false);
						} else {
							jQuery(".saveEventBtn").prop("disabled", true);
							jQuery(".submitEventBtn").prop("disabled", true);
							showInput(true);
						}
						if ($("#registerEventState").val() == "已分配") {
							jQuery(".backEventBtn").prop("disabled", false);
							jQuery(".receiveEventBtn").prop("disabled", false);
							jQuery(".rejectEventBtn").prop("disabled", false);
						} else {
							jQuery(".backEventBtn").prop("disabled", true);
							jQuery(".receiveEventBtn").prop("disabled", true);
							jQuery(".rejectEventBtn").prop("disabled", true);
						}
						if ($("#registerEventState").val() == "已退回") {
							jQuery(".rejectBackEventBtn").prop("disabled",
									false);
						} else {
							jQuery(".rejectBackEventBtn")
									.prop("disabled", true);
						}
						if ($("#registerEventState").val() == "已完结") {
							jQuery('#completion').show();
							showCompletion(eventRegisterIdentify);
						}else{
							jQuery('#completion').hide();
							cleanArcheve();
						}
						
						if(eventReportIdentify == '' || eventRegisterIdentify == ''){
							jQuery('.contrastBtn').prop("disabled", true);
						}else{
							jQuery('.contrastBtn').prop("disabled", false);
							getContrast(eventRegisterIdentify);
						}
						
						getProcedure(eventRegisterIdentify);
						
					}
				}
			});
};

function showInput(flag){
	jQuery("#registerEventName").prop("disabled", flag);
	jQuery("#registerEventEvaluateLevel").prop("disabled", flag);
	jQuery("#registerEventSeriousLevel").prop("disabled", flag);
	jQuery("#registerEventReportTime").prop("disabled", flag);
	jQuery("#dateTime").prop("disabled", flag);
	jQuery("#acceptLimitSpan").prop("disabled", flag);
	jQuery("#dealLimitSpan").prop("disabled", flag);
	if(flag){
		jQuery('#registerEventTypeBtn').hide();
		jQuery('#registerEventToPartBaseInfoBtn').hide();
	}else{
		jQuery('#registerEventTypeBtn').show();
		jQuery('#registerEventToPartBaseInfoBtn').show();
	}
}

function showCompletion(eventRegisterIdentify){
	$.ajax({
		url : rootPath + "/ui/eventRegister/getCompletion/" + eventRegisterIdentify,
		dataType : 'json',
		data : '',
		type : 'post',
		contentType : "application/json",
		success : function(result) {
			if(result.archive){
				var archive = result.archive;
				jQuery('#dealer').text(archive.dealer.name);
				jQuery('#archiver').text(archive.archiver.name);
				jQuery('#archeveDate').text(moment(archive.archeveDate).format('YYYY/MM/DD HH:mm'));
				jQuery('#archeveContent').val(archive.content);
				jQuery('#archeveMemo').val(archive.memo);
				var photo = archive.photourl;
				if(photo != ""){
					photo =  rootPath + "/" + photo;
				}else{
					photo = "../img/nopicture.png";
				}
				jQuery('#archeveImgAdress').attr('src',photo);
			}else{
				cleanArcheve();
			}
		}
	});
}

function getContrast(eventRegisterIdentify){
	$.ajax({
		url : rootPath + "/ui/eventRegister/getContrast/" + eventRegisterIdentify,
		dataType : 'json',
		data : '',
		type : 'post',
		contentType : "application/json",
		success : function(result) {
			var register = result.register;
			var registerEventImgAdress = "../img/nopicture.png";
			if (register.registerEventImgAdress && register.registerEventImgAdress != "") {
				registerEventImgAdress = window.rootPath + "/" + register.registerEventImgAdress;
			}
			
			var report = register.registerEventToReportEvent;
			var reportImgAdress = "../img/nopicture.png";
			if (report.reportImgAdress && report.reportImgAdress != "") {
				reportImgAdress = window.rootPath + "/" + report.reportImgAdress;
			}
			
			var htmlcontent = '<table class="table table-bordered"><tbody><tr>'
				+ '<td width="50%" align="center">'
				+ '<div width="100%"><div><label align="center"><h3>事件源</h3></label></br>'
				+ '<label align="center">上报人:'+report.reportUser.name+'</label></br>'
				+ '<label align="center">上报时间:'+moment(report.reportAccTime).format('YYYY/MM/DD HH:mm')+'</label></div>'
				+ '<div><img width="250px" src="'+reportImgAdress+'" height="250px" /></div></div>'
				+ '</td>'
				+ '<td width="50%" align="center">'
				+ '<div width="100%"><div><label align="center"><h3>事件详情</h3></label></br>'
				+ '<label align="center">登记人:'+register.registerEventCreateUser.name +'</label></br>'
				+ '<label align="center">登记时间:'+moment(register.registerEventAccTime).format('YYYY/MM/DD HH:mm')+'</label></div>'
				+ '<div><img width="250px" src="'+registerEventImgAdress+'" height="250px" /></div></div>'
				+ '</td></tr>';
			var tasks = result.tasks;
			if(tasks){
				var len = tasks.length;
				if(len > 0){
					for(var i=0; i<len; i++){
						var task = tasks[i];
						var imgAdress = task.photoUrl;
						
						var reportImgAdress = "../img/nopicture.png";
						if (imgAdress && imgAdress != "") {
							imgAdress = window.rootPath + "/" + imgAdress;
						}else{
							imgAdress = window.rootPath + "/img/nopicture.png";
						}
						
						
						var tdNum = i % 2;
						if(tdNum == 0){
							htmlcontent += '<tr>'
						}
						htmlcontent += '<td width="50%" align="center"><div width="100%"><div><label align="center"><h3>'+task.eventTaskOperate+'</h3></label></br>'
							+ '<label align="center">操作人:'+task.eventTaskUser.name +'</label></br>'
							+ '<label align="center">操作时间:'+moment(task.eventTaskTime).format('YYYY/MM/DD HH:mm')+'</label></div>'
							+ '<div><img width="250px" src="'+imgAdress+'" height="250px" /></div></div></td>';
						if(tdNum == 1 || i+1 == len){
							htmlcontent += '</tr>'
						}
					}
				}
			}
			htmlcontent += '</tbody></table>';
			jQuery('#picContrast').append(htmlcontent);
		}
	});
}

function cleanArcheve(){
	jQuery('#dealer').text('');
	jQuery('#archiver').text('');
	jQuery('#archeveDate').text('');
	jQuery('#archeveContent').val('');
	jQuery('#archeveMemo').val('');
	jQuery('#archeveImgAdress').attr('src','../img/nopicture.png');
}
function getFormatDate() {
	var nowDate = new Date();
	var year = nowDate.getFullYear();
	var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1)
			: nowDate.getMonth() + 1;
	var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate
			.getDate();
	return year + "-" + month + "-" + date;
}

function getDateTime() {
	var nowDate = new Date();
	var hours = nowDate.getHours() < 10 ? "0" + (nowDate.getHours() + 1)
			: nowDate.getHours() ;
	var minutes = nowDate.getMinutes() < 10 ? "0" + nowDate.getMinutes() : nowDate
			.getMinutes();
	return hours + ":" + minutes;
}

$("#registerEventEvaluateLevel").change(
		function() {
			initevaluateLevelUserDetail("", $("#registerEventEvaluateLevel")
					.val(), $("#registerEventType").val(), $(
					"#registerEventToNetGrid").val());
		});
jQuery('#fileclick').on('click', function() {
	return $("#file").click();
});
$("#reportImgAdress").error(function() {
	$(this).attr("src", "../img/nopicture.png");
	$(this).error = null;
});
$("#archeveImgAdress").error(function() {
	$(this).attr("src", "../img/nopicture.png");
	$(this).error = null;
});

$("#registerEventImgAdress").error(function() {
	$(this).attr("src", "../img/nopicture.png");
	$(this).error = null;
});
function submitData(registerState, btnClass) {
	jQuery(btnClass).prop("disabled", true);
//	jQuery('#loadingImage').show();
	$("#right").mLoading("showNoIcon");
	/* var registerState = "初始化"; */

	var r = rootPath + '/';
	var registerEventImgAdress = $("#registerEventImgAdress").attr("src").substring(r.length,$("#registerEventImgAdress").attr("src").length);
	if(registerEventImgAdress == '/upload.png' || registerEventImgAdress == '/nopicture.png'){
		registerEventImgAdress = '';
	}
	var eventRegister = {
		"registerEventEvaluateLevel" : {
			"id" : $("#registerEventEvaluateLevel").val()
		},
		"registerEventSeriousLevel" : {
			"id" : $("#registerEventSeriousLevel").val()
		},
		"registerEventName" : $("#registerEventName").val(),
		"registerEventIdentify" : $("#registerEventIdentify").val(),
		"registerEventMemo" : $("#registerEventMemo").val(),
		"registerEventContent" : $("#registerEventContent").val(),
		"acceptLimitSpan" : $("#acceptLimitSpan").val(),
		"dealLimitSpan" : $("#dealLimitSpan").val(),
		"registerEventAdress" : $("#registerEventAdress").val(),
		"longitude" : $("#longitude").val(),
		"latitude" : $("#latitude").val(),
		"registerEventReportTime" : $("#registerEventReportTime").val() + " " + $("#dateTime").val()+":00",
		"registerEventImgAdress" : registerEventImgAdress
	};
	// 这里要注意，这是新增和修改的关键
	if ($("#eventRegisterIdentify").val() != "") {
		eventRegister.id = $("#eventRegisterIdentify").val();
	}
	if ($("#registerEventType").val() != "") {
		eventRegister.registerEventType = {
			"id" : $("#registerEventType").val()
		};
	}

	if ($("#registerEventToNetGrid").val() != "") {
		eventRegister.registerEventToNetGrid = {
			"id" : $("#registerEventToNetGrid").val()
		};
	}
	if ($("#registerEventToPartBaseInfo").val() != "") {
		eventRegister.registerEventToPartBaseInfo = {
			"id" : $("#registerEventToPartBaseInfo").val()
		};
	}
	if ($("#registerEventHierarchy").val() != "") {
		eventRegister.registerEventHierarchy = {
			"id" : $("#registerEventHierarchy").val()
		};
	}

	var tempEvaluate = $(".userdefinedEvaluate");

	var eventToEvaluate = new Array();

	for (var i = 0; i < tempEvaluate.length; i++) {
		var o = {
			"registerEventEvaluateLevel" : {
				"id" : $("#" + tempEvaluate[i].id).attr("userdefinedtype")
			},
			"scale" : tempEvaluate[i].value,
			"registerUser" : {
				"id" : tempEvaluate[i].id
			}
		}
		eventToEvaluate.push(o);
	}

	var data = {};

	var eventReport = $("#eventReportIdentify").val();

	var fileIds = new Array();
	var fileNames = "";
	var formHandle = document.getElementById("mainContent");
	var tagElements = formHandle.getElementsByTagName('input');
	for (var j = 0; j < tagElements.length; j++) {
		element = tagElements[j];
		if ("file" == element.type) {
			fileIds.push(element.id);
			fileNames += element.name + ";";
		}
	}
	data = {
		"registerState" : registerState,
		"eventReport" : eventReport,
		"eventRegister" : JSON.stringify(eventRegister),
		"fileNames" : fileNames,
		"eventToEvaluate" : JSON.stringify(eventToEvaluate),
		"accTime" : $("#registerEventReportTime").val() + " " + $("#dateTime").val() + ":00"
	};

	$.ajaxFileUpload({
		url : window.rootPath + "/ui/eventRegister/saveReportAndRegisterEvent",
		secureuri : false,// 是否需要安全协议
		fileElementId : fileIds,// 文件上传的Id属性
		dataType : 'text',
		data : data,
		success : function(result, status) {
			if (status == "success") {
				message("操作成功");
			} else {
				message("操作失败");
			}
//			jQuery('#loadingImage').hide();
			$("#right").mLoading("hide");
			jQuery(btnClass).prop("disabled", false);
			if ($("#eventRegisterIdentify").val() == "") {
				history.go(-1);
			} else {
				getEventReportData($("#eventReportIdentify").val(), $(
						"#eventRegisterIdentify").val());
			}
		}
	});

	// 设置不提交
	return false;
}
$("body").on(
		"click",
		".saveEventBtn",
		function() {
			if (jQuery("#eventRegisterForm")
					&& !jQuery("#eventRegisterForm").Validform({
						tiptype : 3,
						showAllError : true
					}).check(false)) {
				return;
			}
			var registerState = "初始化";
			submitData(registerState, ".saveEventBtn");
		});
$("body").on(
		"click",
		".submitEventBtn",
		function() {
			if (jQuery("#eventRegisterForm")
					&& !jQuery("#eventRegisterForm").Validform({
						tiptype : 3,
						showAllError : true
					}).check(false)) {
				return;
			}
			var registerState = "已分配";
			submitData(registerState, ".submitEventBtn");
		});
$("body").on("click", ".backEventBtn", function() {
	jQuery('#backModal').modal('show');
});
$("body").on("click", ".rejectEventBtn", function() {
	jQuery('#rejectModal').modal('show');
});
//图片对比
$("body").on("click", ".contrastBtn", function() {
	jQuery('#contrastModal').modal('show');
});

$(".savebackBtn").on(
		'click',
		function() {
			var data = {
				"id" : $("#eventRegisterIdentify").val(),
				"backMemo" : $("#backMemo").val(),
			}
			$.ajax({
				url : rootPath + "/ui/eventRegister/backEventRegister",
				dataType : 'json',
				data : JSON.stringify(data),
				type : 'post',
				contentType : "application/json",
				success : function(result) {
					if (result.data.code <= 0) {
						message("操作失败!");
					} else {
						message(result.data.backStr);
					}
					jQuery('#backModal').modal('hide');

					if ($("#eventRegisterIdentify").val() == "") {
						history.go(-1);
					} else {
						getEventReportData($("#eventReportIdentify").val(), $(
								"#eventRegisterIdentify").val());
					}
				}
			});
		});
$(".saveRejectBtn").on(
		'click',
		function() {
			var data = {
				"id" : $("#eventRegisterIdentify").val(),
				"rejectMemo" : $("#rejectMemo").val(),
			}
			$.ajax({
				url : rootPath + "/ui/eventRegister/rejectEventRegister",
				dataType : 'json',
				data : JSON.stringify(data),
				type : 'post',
				contentType : "application/json",
				success : function(result) {
					if (result.data.code <= 0) {
						message("操作失败!");
					} else {
						message(result.data.rejectStr);
					}
					jQuery('#rejectModal').modal('hide');

					if ($("#eventRegisterIdentify").val() == "") {
						history.go(-1);
					} else {
						getEventReportData($("#eventReportIdentify").val(), $(
								"#eventRegisterIdentify").val());
					}
				}
			});
		});
$("body").on("click",".rejectBackEventBtn",function() {
	jQuery('#rejectBackModal').modal('show');
	$.ajax({
		url : rootPath
				+ "/ui/eventRegister/getRejectBackReason?id="
				+ $("#eventRegisterIdentify").val(),
		dataType : 'json',
		type : 'get',
		contentType : "application/json",
		success : function(result) {
			if (result.data.code <= 0) {
				message("获取退回原因失败!");
			} else {
				if (result.data.reasonStr) {
					$("#rejectBackReason").val(result.data.reasonStr.eventTaskMemo);
					if (result.data.reasonStr.eventTaskUser) {
						$("#rejectBackPerson").val(result.data.reasonStr.eventTaskUser.name);
					}
					var backRegisterImg = "../img/nopicture.png";
					if (result.data.register.registerEventImgAdress && result.data.register.registerEventImgAdress != "") {
						backRegisterImg = window.rootPath + "/" + result.data.register.registerEventImgAdress;
					}
					var backImg = "../img/nopicture.png";
					if (result.data.reasonStr.photoUrl && result.data.reasonStr.photoUrl != "") {
						backImg = window.rootPath + "/" + result.data.reasonStr.photoUrl;
					}
					$('#backRegisterImg').attr('src',backRegisterImg);
					$('#backImg').attr('src',backImg);
					
				}

			}
		}
	});
});
$(".saverejectBackBtn").on(
		'click',
		function() {
			var data = {
				"id" : $("#eventRegisterIdentify").val(),
				"rejectBackMemo" : $("#rejectBackMemo").val(),
			}
			$.ajax({
				url : rootPath + "/ui/eventRegister/rejectBackEventRegister",
				dataType : 'json',
				data : JSON.stringify(data),
				type : 'post',
				contentType : "application/json",
				success : function(result) {
					if (result.data.code <= 0) {
						message("操作失败!");
					} else {
						message(result.data.rejectBackStr);
					}
					jQuery('#rejectBackModal').modal('hide');

					if ($("#eventRegisterIdentify").val() == "") {
						history.go(-1);
					} else {
						getEventReportData($("#eventReportIdentify").val(), $(
								"#eventRegisterIdentify").val());
					}
				}
			});
		});
$("body").on(
		"click",
		".receiveEventBtn",
		function() {
			var data = {
				"id" : $("#eventRegisterIdentify").val()
			}
			$.ajax({
				url : rootPath + "/ui/eventRegister/receiveEventRegister",
				dataType : 'json',
				data : JSON.stringify(data),
				type : 'post',
				contentType : "application/json",
				success : function(result) {
					if (result.data.code <= 0) {
						message("操作失败!");
					} else {
						message(result.data.receiveStr);
					}

					if ($("#eventRegisterIdentify").val() == "") {
						history.go(-1);
					} else {
						getEventReportData($("#eventReportIdentify").val(), $(
								"#eventRegisterIdentify").val());
					}
				}
			});
		});
$("body")
		.on(
				"change",
				"#file",
				function() {
					var $file = $(this);
					var fileObj = $file[0];
					var windowURL = window.URL || window.webkitURL;
					var dataURL;
					var $img = $("#registerEventImgAdress");

					if (fileObj && fileObj.files && fileObj.files[0]) {
						dataURL = windowURL.createObjectURL(fileObj.files[0]);
						$img.attr('src', dataURL);
					} else {
						dataURL = $file.val();
						var imgObj = document.getElementById("preview");
						// 两个坑:
						// 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
						// 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
						imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
						imgObj.filters
								.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;

					}
				});
// 事件类型变化之后切换地图部件图标。
function updatePartIcon(iconAddress) {
	var graphics = map.graphics.graphics;
	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i]) {
			if (graphics[i].pointType == registerPointType) {
				var symbol = graphics[i].symbol;
				symbol.setUrl(iconAddress);
				graphics[i].setSymbol(symbol);
				return;
			}
		}
	}
}
$(".eventTypeConfirmBtn")
		.on(
				'click',
				function() {
					var treeObj = $.fn.zTree.getZTreeObj("eventTree");
					var selectNodes = treeObj.getSelectedNodes(treeObj);
					if (selectNodes) {
						var selectNode = selectNodes[0];
						if (selectNode) {
							var temp_registerEventType=$("#registerEventType").val();
							$("#registerEventTypeName").val(selectNode.name);
							$("#registerEventType").val(selectNode.id);
							updatePartIcon(selectNode.icon);
							// getManagementPersonInfo($("#registerEventType").val(),$("#longitude").val(),$("#latitude").val());
							
							serverDataForUser.eventTypeId = $("#registerEventType").val();
							serverDataForUser.longitude = $("#longitude").val();
							serverDataForUser.latitude = $("#latitude").val();
							serverTableForUser.draw(false);
							
							jQuery("#eventTreeModal").modal('hide');
							var lng = $("#longitude").val();
							var lat = $("#latitude").val();
							if (lng == undefined || lng == "") {
								lng = 0.0;
							}
							if (lat == undefined || lat == "") {
								lat = 0.0;
							}
							$
									.ajax({
										url : rootPath
												+ "/ui/eventRegister/getRealTimeEventIdentify?eventTypeId="
												+ $("#registerEventType").val()
												+ "&longitude=" + lng
												+ "&latitude=" + lat,
										dataType : 'json',
										type : 'get',
										contentType : "application/json",
										success : function(result) {
											if (result.data.codeForEventIdentify <= 0) {
												message("实时获取事件编码失败!");
											} else {
												$("#registerEventIdentify")
														.val(
																result.data.eventIdentify);
											}
										}
									});
							if(temp_registerEventType!=selectNode.id){
								initevaluateLevelUserDetail("", $("#registerEventEvaluateLevel")
										.val(), $("#registerEventType").val(), $(
										"#registerEventToNetGrid").val());
							}
						} else {
							message("请选择事件类型");
						}
					} else {
						message("请选择事件类型");
					}

				});
$("#registerEventTypeBtn").on(
		'click',
		function() {
			jQuery("#eventTreeModal").modal('show');

			// 初始化 层级树
			var primaryNode = [];
			var url = window.rootPath + '/ui/eventType/getAllNodes';
			jQuery
					.ajax({
						url : url,
						cache : false,
						type : "get",
						data : '',
						dataType : "json",
						contentType : 'application/json;charset=utf-8',// 解决返回数据中的中文乱码问题
						success : function(data) {
							primaryNode.push({
								id : 0,
								name : "事件层级",
								open : "true",
								icon : defaultEventIcon
							// iconSkin:"diy03"
							});
							for (var i = 0; i < data.nodes.length; i++) {
								if (data.nodes[i].iconAddress != undefined
										&& data.nodes[i].iconAddress != "") {
									data.nodes[i].icon = window.rootPath + "/"
											+ data.nodes[i].iconAddress;
								} else {
									data.nodes[i].icon = defaultEventIcon;
								}
								primaryNode.push(data.nodes[i]);
							}

							$.fn.zTree.init($("#eventTree"), modalSetting,
									primaryNode);

							var treeObj = $.fn.zTree.getZTreeObj("eventTree");
							var node = treeObj.getNodeByParam("id", $(
									"#registerEventType").val(), null);
							treeObj.selectNode(node);
							treeObj.expandNode(node, true, true, true);
						}
					});
		});

// 当网格和事件发生变化时候，重新查找管理人员

var serverDataForUser = {};
var serverTableForUser;

function getManagementPersonInfo(registerEventType, longitude, latitude) {

	if(longitude==""){
		longitude=0
	} 
	if(latitude==""){
		latitude=0
	} 
	serverDataForUser.eventTypeId = registerEventType;
	serverDataForUser.longitude = longitude;
	serverDataForUser.latitude = latitude;

	serverTableForUser = jQuery('#userDataTable')
			.DataTable(
					{
						"serverSide" : true,
						"ordering" : false,
						"ajax" : {
							"dataType" : "json",
							"type" : "get",
							"cache" : false,
							"url" : window.rootPath
									+ '/ui/eventRegister/getManagmentPersonByEventTypeAndGrid',
							"data" : function(d) {
								return $.extend({}, d, serverDataForUser);
							}
						},
						columns : [ {
							data : null
						}, {
							data : 'name'
						}, {
							data : 'sex'
						}, {
							data : 'contactType'
						}, {
							data : 'email'
						}, {
							data : 'state.hierarchy.groupName'
						} ],
						"drawCallback" : function(oSettings) {
							var k = 0;
							var total = oSettings.aiDisplay.length
									+ oSettings._iDisplayStart;

							for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
								$(
										'td:eq(0)',
										oSettings.aoData[oSettings.aiDisplay[k]].nTr)
										.text(i + 1);
								k++;
							}
							serverTableForUser.off('click', 'tr');
							serverTableForUser.on('click', 'tr',
									function(event) {
										event = event || window.event;
										var target = event.target
												|| event.scrElement;
										var data = serverTableForUser.row(this)
												.data();
										return;
									});
						}
					});
}
$("#registerEventToPartBaseInfoBtn")
		.on(
				'click',
				function() {
					jQuery("#partModal").modal('show');

					// 初始化 层级树
					var primaryNode = [];
					var url = window.rootPath + '/ui/part/getAllNodes';
					jQuery.ajax({
						url : url,
						cache : false,
						type : "get",
						data : '',
						dataType : "json",
						contentType : 'application/json;charset=utf-8',// 解决返回数据中的中文乱码问题
						success : function(data) {
							primaryNode.push({
								id : 0,
								name : "部件层级",
								open : "true",
								icon : defaultPartIcon
							});
							for (var i = 0; i < data.nodes.length; i++) {
								if (data.nodes[i].iconAddress != undefined
										&& data.nodes[i].iconAddress != "") {
									data.nodes[i].icon = window.rootPath + "/"
											+ data.nodes[i].iconAddress;
								} else {
									data.nodes[i].icon = defaultPartIcon;
								}
								primaryNode.push(data.nodes[i]);
							}
							$.fn.zTree.init($("#partTree"), partModalSetting,
									primaryNode);

							var treeObj = $.fn.zTree.getZTreeObj("partTree");
							// var node =
							// treeObj.getNodeByParam("id",$("#registerEventType").val(),
							// null);
							// treeObj.selectNode(node);
							// treeObj.expandNode(node, true, true, true);
						}
					});

					serverData.gridId = jQuery('#registerEventToNetGrid').val();
					serverData.partId = '';

					serverTable = jQuery('#dataTable')
							.DataTable(
									{
										"serverSide" : true,
										"ordering" : false,
										"ajax" : {
											"dataType" : "json",
											"type" : "post",
											"cache" : false,
											"url" : window.rootPath
													+ '/ui/eventRegister/getpagebypartandgrid',
											"data" : function(d) {
												return $.extend({}, d,
														serverData);
											}
										},
										columns : [
												{
													data : null,
													defaultContent : ""
												},
												{
													data : {},
													render : function(data,
															type, full, meta) {
														var operate = '<input type="checkbox" dataId="'
																+ data.id
																+ '" dataName="'
																+ data.partName;
														if (data.hierarchy) {
															operate += '" hierarchyId="'
																	+ data.hierarchy.id
																	+ '" hierarchyName="'
																	+ data.hierarchy.groupName
																	+ '"  group="part"/>';
														} else {
															operate += '" hierarchyId="" hierarchyName=""  group="part"/>';
														}

														return operate;
													}
												},
												{
													data : 'partName'
												},
												{
													data : 'manufacturer'
												},
												{
													data : 'productionTime',
													render : function(data,
															type, full, meta) {
														if (data)
															return moment(data)
																	.format(
																			'YYYY/MM/DD');
														else
															return '';
													}
												},
												{
													data : 'installationTime',
													render : function(data,
															type, full, meta) {
														if (data)
															return moment(data)
																	.format(
																			'YYYY/MM/DD');
														else
															return '';
													}
												},
												{
													data : 'division.divisionName',
												}, {
													data : 'part.partName'
												}, {
													data : 'state.title'
												} ],
										"drawCallback" : function(oSettings) {
											var k = 0;
											var total = oSettings.aiDisplay.length
													+ oSettings._iDisplayStart;

											for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
												$(
														'td:eq(0)',
														oSettings.aoData[oSettings.aiDisplay[k]].nTr)
														.text(i + 1);
												k++;
											}
											// 时限 checkbox 单选
											$(":checkbox[group=part]")
													.click(
															function() {
																var part = $(":checkbox[group=part]");
																if ($(this)
																		.prop(
																				"checked")) {
																	part
																			.prop(
																					"checked",
																					false);
																	$(this)
																			.prop(
																					"checked",
																					true);
																}
															});

											serverTable.off('click', 'tr');
											serverTable
													.on(
															'click',
															'tr',
															function(event) {
																event = event
																		|| window.event;
																var target = event.target
																		|| event.scrElement;
																var data = serverTable
																		.row(
																				this)
																		.data();
																return;
															});
										}
									});

				});
function getPartBaseInfo(e, treeId, treeNode) {
	var Id = treeNode.id;
	if ('0' == Id)
		return;
	serverData.partId = Id;
	serverTable.draw();
}

$(".partConfirmBtn").on('click', function() {
	var obj = $(":checkbox[group=part]:checked");
	if (obj.length == 0) {
		message("请选择部件!");
		return;
	}
	jQuery("#partModal").modal('hide');
	jQuery("#registerEventToPartBaseInfoName").val(obj.attr('dataName'));
	jQuery("#registerEventToPartBaseInfo").val(obj.attr('dataId'));

	var hierarchyId = obj.attr('hierarchyId');
	if (hierarchyId != "") {
		jQuery("#registerEventHierarchyName").val(obj.attr('hierarchyName'));
		jQuery("#registerEventHierarchy").val(obj.attr('hierarchyId'));
	}

});
// //////////////初始化模型的树结构/////////////////////////
var partModalSetting = {
	edit : {
		enable : false,
		showRemoveBtn : false,
		showRenameBtn : false,
	},
	data : {
		simpleData : {
			enable : true,
			idKey : "id",
			pIdKey : "parentId",
			rootParentId : 0
		}
	},
	view : {
		showLine : true
	},
	check : {
		enable : false,
		chkStyle : "radio",
		radioType : "level"
	},
	callback : {
		onClick : getPartBaseInfo,
		onNodeCreated : zTreeOnNodeCreated
	}

};

// //////////////初始化模型的树结构/////////////////////////
var modalSetting = {
	data : {
		simpleData : {
			enable : true,
			idKey : "id",
			pIdKey : "parentId",
			rootParentId : 0
		}
	},
	view : {
		showLine : true
	},
	callback : {
		onNodeCreated : zTreeOnNodeCreated
	}

};
// 设置tree图标大小
function zTreeOnNodeCreated(event, treeId, treeNode) {
	if (treeNode.type != "folder") {
		$('#' + treeNode.tId + '_ico').css(
				"background",
				"url('" + treeNode.icon
						+ "') center center/16px 16px no-repeat");
	}
}
/*-----------------------------------百度地图------------------------------------------*/
// 打开弹窗
var marker;
jQuery('#registerEventAdressBtn').on('click', function() {
	jQuery("#mapforbaidu").modal('show');
	var longitude = jQuery("#longitude").val();
	var latitude = jQuery("#latitude").val();
	if (!longitude || !latitude) {
		longitude = 106.5254080000; // lng 经度
		latitude = 29.5217230000; // lat 维度
	}
	var map = new BMap.Map("allmap");
	var point = new BMap.Point(longitude, latitude);
	map.centerAndZoom(point, 12);
	map.enableScrollWheelZoom();
	map.enableInertialDragging();
	map.enableContinuousZoom();

	var markerPoint = new BMap.Point(longitude, latitude);
	BMap.Convertor.translate(markerPoint, 0, function initMap(point){ 
		marker = new BMap.Marker(point);// 创建标注
		marker.enableDragging();
		map.addOverlay(marker); // 将标注添加到地图中
		}); //转换坐标 
	
}); 
function getAdress(longitude,latitude){
	
	var markerPoint = new BMap.Point(longitude, latitude);
	BMap.Convertor.translate(markerPoint, 0, function initMap(point){ 
		// 逆地址解析
		var geoc = new BMap.Geocoder();
		geoc.getLocation(point, function(rs) {
			var addComp = rs.addressComponents;
			jQuery("#registerEventAdress").val(
					addComp.province + ", " + addComp.city + ", "
							+ addComp.district + ", "
							+ addComp.street + ", "
							+ addComp.streetNumber);
		});
		}); //转换坐标 
}
jQuery(".getLaction")
		.on(
				"click",
				function() {
					var p = marker.getPosition(); // 获取marker的位置
					jQuery("#longitude").val(p.lng);
					jQuery("#latitude").val(p.lat);

					// 逆地址解析
					var newpoint = new BMap.Point(p.lng, p.lat);
					var geoc = new BMap.Geocoder();
					geoc.getLocation(newpoint, function(rs) {
						var addComp = rs.addressComponents;
						jQuery("#registerEventAdress").val(
								addComp.province + ", " + addComp.city + ", "
										+ addComp.district + ", "
										+ addComp.street + ", "
										+ addComp.streetNumber);
					});
					jQuery("#mapforbaidu").modal('hide');

					$
							.ajax({
								url : rootPath
										+ "/ui/eventRegister/getRealTimeEventIdentify?eventTypeId="
										+ $("#registerEventType").val()
										+ "&longitude=" + $("#longitude").val()
										+ "&latitude=" + $("#latitude").val(),
								dataType : 'json',
								type : 'get',
								contentType : "application/json",
								success : function(result) {
									if (result.data.codeForEventIdentify <= 0) {
										message("实时获取事件编码失败!");
									} else {
										$("#registerEventIdentify").val(
												result.data.eventIdentify);
									}
									if (result.data.codeForGrid <= 0) {
										message("实时获取网格失败!");
									} else {
										if (result.data.gridInfo) {
											$("#registerEventToNetGridName")
													.val(
															result.data.gridInfo.gridName);
											$("#registerEventToNetGrid").val(
													result.data.gridInfo.id);
										}

									}
								}
							});
				});


function getProcedure(id) {
	$("#procedureB").empty();
	$.ajax({
		url : rootPath + '/ui/eventRegister/getProcedure/' + id,
		dataType : 'json',
		type : 'get',
		success : function(result) {
			if (result.code == 1) {
				var list = result.data.procedures;
				$.each(list, function() {
					var tr = $("<tr></tr>");
					var opTd = $("<td>" + this.eventTaskOperate + "</td>");
					var stateTd = $("<td>" + this.eventTaskState.title
							+ "</td>");
					var timeTd = $("<td>"
							+ moment(this.eventTaskTime).format(
									"YYYY/MM/DD HH:mm") + "</td>");
					var userTd = $("<td>" + this.eventTaskUser.name + "</td>");
					$("#procedureB").append(tr).append(opTd).append(stateTd)
							.append(timeTd).append(userTd);
				});
			}
		}
	})
	// $("#detailsShow").show();
};

$('.lot-time').datetimepicker({
    format: "yyyy/mm/dd HH:mm",
    todayBtn: "linked",
    minuteStep: 1,
    autoclose: true
});


$(document).on('mouseenter','img',function(){
	var type = $(this).attr('data-type');
	if(type == 'page'){
		$($(this).attr('data-div')).append("<p id='pic'><img src='"+this.src+"' id='pic1'></p>");
		$("img").mousemove(function(e){
			$("#pic").css({
//	            "top":'calc(50% - 300px)',
//	            "left":'calc(50% - 300px)'
				"top":$(document).scrollTop()+100+'px',
                "left":"calc(50% - 300px)"
	        }).fadeIn("fast");
		});
	}
});

$(document).on('mouseleave','img',function(){
	var type = $(this).attr('data-type');
	if(type == 'page'){
		$("#pic").remove();
	}
});

